<?php
use Grafika\Grafika;

/**
 * 判断是否是window操作系统
 * @return bool
 */
function is_windows() : bool {
    return strtoupper(substr(PHP_OS,0,3))==='WIN';
}

/**
 * 遍历文件
 * @param string $basePath 根路径
 * @param string $path 要遍历的路径
 * @param int $level 要遍历的层级
 * @param int $docType 0:全部 1:文件 2:目录
 * @return array
 */
function scan_files($basePath, $path, $level = 1, $docType = 0) : array
{
    //判断目录是否为空
    $fullPath = trim($basePath . DIRECTORY_SEPARATOR . $path, DIRECTORY_SEPARATOR);

    if(!file_exists($fullPath)) {
        return [];
    }

    $fileItem = [];

    $oldPath = getcwd();
    //切换如当前目录
    chdir($fullPath);
    $level = $level - 1;

    foreach(glob('*') as $v) {
        $newPath = $fullPath . DIRECTORY_SEPARATOR . $v;
        $urlPath = trim($path.DIRECTORY_SEPARATOR.$v, DIRECTORY_SEPARATOR);
        $file = [
            'name'  => $v,
            'path'  => $urlPath,
        ];
        $isDir = is_dir($newPath);

        if ($isDir) {
            if ($docType != 1) {
                if ($level > 0) {
                    $files          = scan_files($basePath, $urlPath, $level, $docType);
                    $file['children']  = $files;
                } else {
                    $file['children']  = null;
                }
            } else {
                continue;
            }
        } else {

            if ($docType == 2) {
                continue;
            }
        }

        $fileItem[] = $file;
    }

    // 回到原始CMD
    chdir($oldPath);
    return $fileItem;
}

/**
 * @param string $in
 * @param string $out
 * @param int $width
 * @param int $height
 * @throws Exception
 */
function resizeImage($in, $out, $width=0, $height=0) {
    $editor = Grafika::createEditor();
    $editor->open($img, $in);

    if ($width == 0 && $height > 0) {
        $editor->resizeExactHeight($img, $height);
    } elseif ($width > 0 && $height == 0) {
        $editor->resizeExactWidth($img, $width);
    } elseif ($width > 0 && $height > 0) {
        $editor->resize($img, $width, $height);
    } else {
        $editor->resizeExactWidth($img, 200);
    }
    $editor->save($img, $out);
}
